
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

public class MBeansClient {

	public static void main(String[] args) throws Exception {
		List<VirtualMachineDescriptor> vms = VirtualMachine.list();
		for (VirtualMachineDescriptor desc : vms) {
			VirtualMachine vm;
			try {
				vm = VirtualMachine.attach(desc);
			} catch (AttachNotSupportedException e) {
				continue;
			}
			Properties props = vm.getAgentProperties();
			String connectorAddress = props
					.getProperty("com.sun.management.jmxremote.localConnectorAddress");
			if (connectorAddress == null) {
				continue;
			}
			JMXServiceURL url = new JMXServiceURL(connectorAddress);
			JMXConnector connector = JMXConnectorFactory.connect(url);
			try {
				MBeanServerConnection mbeanConn = connector
						.getMBeanServerConnection();
				Set<ObjectName> beanSet = mbeanConn.queryNames(null, null);
				for (ObjectName bean : beanSet)
					System.out.println(bean);

				ObjectName name = new ObjectName(
						"quickstarts:type=AnnotatedComponentHelloWorld");
				String s = (String) mbeanConn.getAttribute(name,
						"WelcomeMessage");
				System.out.println(s);
			} finally {
				connector.close();
			}
		}
	}

}
